#pragma once

#include <ode/ode.h>
#include <irrlicht.h>
using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

namespace dalelib
{

class IrrlichtBox
{
private:

public:

	IAnimatedMeshSceneNode* _node;
	dMass _mass;
	dBodyID _body;
	dGeomID _geom;


	IrrlichtBox(
		const dWorldID _World,
		const dSpaceID _Space,
		scene::ISceneManager* _SceneManager,
		IAnimatedMesh* _Mesh,
		const vector3df _Size,
		const vector3df _Pos )
	{
		_node = _SceneManager->addAnimatedMeshSceneNode( _Mesh );
		_node->setPosition( _Pos );
		_node->setScale( _Size );
		_node->setMaterialFlag( EMF_LIGHTING, true );
		_node->setMaterialFlag( EMF_FOG_ENABLE, true );
		_node->addShadowVolumeSceneNode();

//		vector3df extend = _node->getBoundingBox().getExtent();
		vector3df extend = _Size*2.f;
		vector3df pos = _node->getPosition();
		_geom = dCreateBox( _Space, (dReal)extend.X, (dReal)extend.Y, (dReal)extend.Z );
		dGeomSetPosition( _geom, pos.X, pos.Y, pos.Z );
		dGeomSetData( _geom, _node );
		_body = dBodyCreate( _World );
		dMassSetBox( &_mass, 2.0f, (dReal)extend.X, (dReal)extend.Y, (dReal)extend.Z );
		dBodySetMass( _body, &_mass );
		dGeomSetBody( _geom, _body );
		dBodySetPosition( _body, _Pos.X, _Pos.Y, _Pos.Z );
		dBodySetData( _body, _node );
	}


	void update()
	{
		static irr::core::vector3df rot;

		if( dGeomIsEnabled( _geom ) )
		{
			dReal* ode_pos =(dReal*)dGeomGetPosition( _geom );
			ISceneNode *node = (ISceneNode*)dGeomGetData( _geom );
			vector3df pos( (irr::f32)ode_pos[0], (irr::f32)ode_pos[1], (irr::f32)ode_pos[2] );
			node->setPosition( pos );
			//ODE uses quaternions, so we get it and convert to euler
			dQuaternion result;
			dGeomGetQuaternion( _geom, result );
			irr::core::quaternion quat( result[1], result[2], result[3], result[0] );
			quat.toEuler( rot );
			static float deg2rad = 180.f/PI;
			vector3df deg( rot.X*deg2rad, rot.Y*deg2rad, rot.Z*deg2rad );
			node->setRotation( deg );
		}
	}

};



} // namespace dalelib
